// pages/order/order.js
const app = getApp();

let api = require('../../utils/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentIndex: 0,
    "firstList": [],
    "secondList": [],
    "thirdList": [],
    "fourthList": [],
    pageNum: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    app.getRemind()
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight - app.globalData.navHeight,
          listHeight: ((res.windowHeight - app.globalData.navHeight) * 2 - 88) / 2
        });
      }
    });

    that.setData({
      currentIndex: 0
    });

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    var that = this;
    var state = [],
      total = [],
      name = [];
    state = [1, 2, 3, 4];
    total = ['firstListTotal', 'secondListTotal', 'thirdListTotal', 'fourthListTotal'];
    name = ['firstList', 'secondList', 'thirdList', 'fourthList'];
    var token = wx.getStorageSync('TOKEN');

    var param = {
      state: state[that.data.currentIndex],
      pageNum: 1,
      pageSize: 5
    };
    that.orderTotal(token);
    that.getOrderList(state[that.data.currentIndex], param, wx.getStorageSync('TOKEN'), total[that.data.currentIndex], name[that.data.currentIndex]);

  },
  //swiper切换时会调用
  pagechange: function (e) {
    if ("touch" === e.detail.source) {
      let currentPageIndex = this.data.currentIndex
      currentPageIndex = (currentPageIndex + 1) % 5
      this.setData({
        currentIndex: currentPageIndex
      })
    }
  },
  //用户点击tab时调用
  titleClick: function (e) {
    var that = this;
    that.setData({
      //拿到当前索引并动态改变
      currentIndex: e.currentTarget.dataset.idx
    })
    var item = e.currentTarget.dataset.total;
    var dataList = e.currentTarget.dataset.listname;
    var param = {
      state: e.currentTarget.dataset.state,
      pageNum: 1,
      pageSize: 5
    };
    that.setData({
      pageNum: 1
    })
    var token = wx.getStorageSync('TOKEN')
    that.orderTotal(token)
    that.getOrderList(e.currentTarget.dataset.state, param, token, item, dataList);
  },
  // 禁止用户左右滑动
  catchTouchMove: function (res) {
    return false
  },
  // 订单详情
  openDetail: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.gid;
    wx.navigateTo({
      url: 'userOrderDetail/orderDetail?id=' + id
    })
  },
  // 获取订单统计数
  orderTotal: function (token) {
    var that = this;
    api._get('/omc/order/total', '', token).then(res => {
      if (res.code == 200) {
        that.setData({
          firstListTotal: res.result.haveOrderTotal, // 已接单总数
          secondListTotal: res.result.awaitShipmentsTotal, // 代发货总数
          thirdListTotal: res.result.awaitReceiptTotal, // 待接单总数
          fourthListTotal: res.result.doneTotal, // 已完成总数
        })
      } else if (res.code > 400) {
        wx.navigateTo({
          url: '../login/login',
        })
      } else {
        wx.showToast({
          title: '网络忙请重试',
          icon: 'none',
        })
      }
    })
  },
  // 获取订单列表
  getOrderList: function (idx, param, token, item, dataList, loadMore) {
    var that = this;
    var stateData = [];
    stateData[0] = '待接货';
    stateData[1] = '已接单';
    stateData[2] = '已装货';
    stateData[3] = '待发货';
    stateData[4] = '待收货';
    stateData[5] = '已达到';
    stateData[6] = '待评价';
    api._get('/omc/order/list/' + idx, param, token).then(res => {
      if (res.code == 200) {
        var list = res.result;
        list.forEach(function (value, index) {
          var createTime = value.createTime * 1000;
          var shipmentTime = value.shipmentTime.end * 1000;
          list[index]['createTime'] = app.formatDate(createTime, 'YYYY-MM-DD H:m:s')
          list[index]['showShipmentTime'] = app.formatDate(shipmentTime, 'YYYY-MM-DD');
          if (value.state < 0) {
            list[index]['showState'] = '取消中';
          } else {
            if (value.state == 6) {
              if (value.isEvaluate == 0) {
                list[index]['showState'] = '待评价';
              } else {
                list[index]['showState'] = '已评价';
              }
            } else {
              list[index]['showState'] = stateData[list[index]['state']];
            }
          }
          if (value.freightWeight.max && value.freightWeight.min) {
            list[index]["showfreightWeight"] = value.freightWeight.min + '-' + value.freightWeight.max + '吨';
          } else if (value.freightWeight.max && !value.freightWeight.min) {
            list[index]["showfreightWeight"] = value.freightWeight.max + '吨';
          } else if (!value.freightWeight.max && value.freightWeight.min) {
            list[index]["showfreightWeight"] = value.freightWeight.min + '吨';
          }
        });
        if (loadMore) {
          if (param.pageNum <= res.page.totalPage) {
            var showData = [...that.data[dataList], ...list];
            that.setData({
              [dataList]: showData
            })
          } else {
            wx.showToast({
              title: '没有更多订单',
              icon: 'none'
            })
            return false
          }
        } else {
          that.setData({
            [dataList]: list
          })
        }

      } else if (res.code > 400) {
        wx.navigateTo({
          url: '../login/login',
        })
      } else {
        wx.showToast({
          title: '网络忙请重试',
          icon: 'none',
        })
      }

    })
  },
  /**
   * 打电话
   */
  callExpert: function (e) {
    // console.log(e.currentTarget.dataset.phone)
    var phone = e.currentTarget.dataset.phone;
    app.callExpert(phone);
  },
  /**
   * 订单操作
   */
  orderAction: function (e) {
    var that = this;

    var state1 = [],
      total = [],
      name = [];
    state1 = [1, 2, 3, 4];
    total = ['firstListTotal', 'secondListTotal', 'thirdListTotal', 'fourthListTotal'];
    name = ['firstList', 'secondList', 'thirdList', 'fourthList'];
    var token = wx.getStorageSync('TOKEN');
    var params = {
      id: e.currentTarget.dataset.orderid,
      state: parseInt(e.currentTarget.dataset.state),
      token: token
    }

    app.orderAction(params).then(function (code) {
      if (code == 200) {
        that.orderTotal(token)

        var param = {
          state: state1[that.data.currentIndex],
          pageNum: 1,
          pageSize: 5
        };
        that.getOrderList(state1[that.data.currentIndex], param, token, total[that.data.currentIndex], name[that.data.currentIndex])

        that.setData({
          pageNum: 1
        })
      }
    })

  },
  // 下拉操作
  onRefresh: function (e) {
    var callback = e.detail;
    var that = this;
    var state = [],
      total = [],
      name = [];
    state = [1, 2, 3, 4];
    total = ['firstListTotal', 'secondListTotal', 'thirdListTotal', 'fourthListTotal'];
    name = ['firstList', 'secondList', 'thirdList', 'fourthList'];
    var param = {
      state: state[that.data.currentIndex],
      pageNum: 1,
      pageSize: 5
    };
    that.setData({
      pageNum: 1
    })
    setTimeout(function () {
      that.getOrderList(state[that.data.currentIndex], param, wx.getStorageSync('TOKEN'), total, name[that.data.currentIndex]);
      that.orderTotal(wx.getStorageSync('TOKEN'))
      callback.success();
    }, 3000)
  },
  // 上拉加载更多
  onLoadMore: function (e) {
    var callback = e.detail;
    var that = this;
    var state = [],
      total = [],
      name = [];
    state = [1, 2, 3, 4];
    total = ['firstListTotal', 'secondListTotal', 'thirdListTotal', 'fourthListTotal'];
    name = ['firstList', 'secondList', 'thirdList', 'fourthList'];
    var param = {
      state: state[that.data.currentIndex],
      pageNum: that.data.pageNum + 1,
      pageSize: 5
    };
    that.setData({
      pageNum: that.data.pageNum + 1
    })
    setTimeout(function () {
      that.getOrderList(state[that.data.currentIndex], param, wx.getStorageSync('TOKEN'), total, name[that.data.currentIndex], true);
      that.orderTotal(wx.getStorageSync('TOKEN'))
      callback.success();
    }, 2000)
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    console.log(res);
    if (res.from === 'button') {
      this.setData({
        showShareModelStatus: false
      })
    } else if (res.from === 'menu') {
      console.log(res.from);
      console.log('右上角菜单转发按钮');
    }
  },
})